package red.mlz.uploadservice.service;

import com.aliyun.oss.OSS;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class OssService {
    private final OSS ossClient;
    @Value("${aliyun.oss.bucket-name}")
    private  String bucketName;

    @Value("${aliyun.oss.endpoint}")
    private  String endpoint;


    public OssService(OSS ossClient) {
        this.ossClient = ossClient;
    }

    public String upload(MultipartFile file, Integer width, Integer height) throws IOException {
        String objectKey = generateObjectKey(file, width, height);
        try (InputStream inputStream = file.getInputStream()) {
            ossClient.putObject(bucketName, objectKey, inputStream);
        }
        return generateUrl(objectKey);
    }

    /**
     * 智能生成对象路径
     */
    private String generateObjectKey(MultipartFile file, Integer width, Integer height) {
        boolean isImage = isImageFile(file);
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMM/dd"));
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String extension = getFileExtension(file.getOriginalFilename());

        if (isImage) {
            String sizeSuffix = (width != null && height != null) ?
                    "_" + width + "x" + height : "";
            return String.format("image/%s/%s%s.%s", datePath, uuid, sizeSuffix, extension);
        } else {
            return String.format("file/%s/%s.%s", datePath, uuid, extension);
        }
    }

    /**
     * 判断是否为图片文件（基于MIME类型）
     */
    private boolean isImageFile(MultipartFile file) {
        String contentType = file.getContentType();
        return contentType != null && contentType.startsWith("image/");
    }

    private String generateUrl(String objectKey) {
        return String.format("https://%s.%s/%s",
                bucketName,
                endpoint,
                objectKey
        );
    }
    /**
     * 获取安全的文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return "file"; // 无扩展名时默认
        }
        return filename.substring(filename.lastIndexOf(".") + 1);
    }
}
